#include "tools.h"
#include "myinet.h"
#include <unistd.h>
#include <stdlib.h>
#include <time.h>

int
main(int argc, char** argv) {
    
    int sockfd, n;

    int portNumber;
    struct sockaddr_in accept_addr;
    socklen_t accept_addr_len;

    if (argc < 3){
        printf("Usage: %s <address> <port> \n", argv[0]);
        error_exit("please use the above format", NULL);
    }

    portNumber = atoi(argv[2]);

    char buffer[256];
    // 构建地址
    struct in_addr a_in_addr;
    get_in_addr_by_name_or_ip(argv[1], &a_in_addr);

    sockfd = connectTo(a_in_addr, portNumber, SOCK_DGRAM);

    info("connect %s:%d\n", inet_ntoa(a_in_addr), portNumber);

    printf("input message>");
    fflush(stdout);
    while ((n = read(STDIN_FILENO, buffer, sizeof(buffer))) > 0){
     
        info("sending request");
        write(sockfd, buffer, n);
        info("done sending request");

        int r;
        info("waiting for response");
        if (( r = recv(sockfd, buffer, sizeof(buffer), 0)) < 0) {
            error_exit("recv",0);
        }
        printf("received:%s\n", buffer);
        printf("input message>");
        fflush(stdout);
    }
    

    return 0;
}
